/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.contorller;

import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.portal.common.restfull.RequestMapping;
import com.apache.portal.common.restfull.ResultFullAnntation;
import com.apache.portal.common.restfull.SupperAction;
import com.apache.portal.common.template.BuildProjectFactory;
import com.apache.portal.common.template.CreateTableSql;
import com.apache.portal.common.template.FreemarkerHelper;
import com.apache.portal.common.util.FileOperate;
import com.apache.portal.thread.FileOperateUtil;
import com.apache.tools.ConfigUtil;
import com.apache.tools.DataMap;
import com.apache.tools.FileZipUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * description:
 *
 * @author cbqiu 创建时间：2016-11-3
 */
@SuppressWarnings("serial")
@ResultFullAnntation(name = "codingAction", urlPatterns = { "/common/coding/*" })
public class CodingAction extends SupperAction {

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     */
    protected void doInvoke(HttpServletRequest request, HttpServletResponse response,
            String methodType) throws Exception {
        Method method = doInvoke(this.getClass(), request, response, methodType, "");
        if (null != method) {
            log.info("start doInvoke ["+method.getName()+"] ["+methodType+"].....");
            Object obj = method.invoke(this, request, response);
            if (!ToolsUtil.isEmpty(obj)) {
                JSONObject array = JSONObject.fromObject(obj);
                this.outputJson(array.toString(), response, request.getParameter("callback"));
            }
        } else {
            gotoErrorPage(request, response, "请求的Action地址未定义");
        }
    }

    @RequestMapping(value = "buildProject", method = "post")
    public ResultMsg buildProject(HttpServletRequest request, HttpServletResponse response) {
        String ids = request.getParameter("tempIds");
        String filePath = request.getParameter("filePath");
        String projectName = request.getParameter("projectName");
        String packPath = request.getParameter("packPath");
        String createTemplate = request.getParameter("createTemplate");
        String templateName = request.getParameter("templateName");
        Map<String, String> param = new HashMap<String, String>();
        param.put("filePath", filePath);
        param.put("ids", ids);
        param.put("projectName", projectName);
        param.put("packPath", packPath);
        param.put("createTemplate", createTemplate);
        param.put("templateName", templateName);
        boolean mark = BuildProjectFactory.instance().ctreateProject(param);
        ResultMsg rmsg = new ResultMsg("F", "工程生成失败！");
        if (mark) {
            rmsg = new ResultMsg("F", "工程生成成功！");
        }
        return rmsg;
    }

    //创建工程
    @RequestMapping(value = "buildProjects", method = "post")
    public ResultMsg buildProjects(HttpServletRequest request, HttpServletResponse response) {
        String tempId = request.getParameter("templateId");
        if (StrUtil.isNull(tempId)) {
            return new ResultMsg("F", "缺少方法参数");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> paramVo = new HashMap<String, Object>();
        paramVo.put("sysTemplate.w_templateId", tempId);
        paramVo.put("modelTypes", "s_sysTemplate");
        List<Map> list = (List) BuildProjectFactory.instance().init(paramVo);
        if (ToolsUtil.isEmpty(list)) {
            return new ResultMsg("F", "没有获取到定义的模板");
        }
        Map temp = list.get(0);
        map.put("template", temp);

        paramVo = new HashMap<String, Object>();
        paramVo.put("sysTemplateInfo.w_templateId", tempId);
        paramVo.put("modelTypes", "s_sysTemplateInfo");
        paramVo.put("orderBy", "sysTemplateInfo.tab_no asc");
        List<Map> listDetial = (List) BuildProjectFactory.instance().init(paramVo);
        if (ToolsUtil.isEmpty(list)) {
            return new ResultMsg("F", "没有获取到定义的模板详情");
        }
        map.put("detail", listDetial);

        boolean mark = BuildProjectFactory.instance().ctreateProjects(map);
        ResultMsg rmsg = new ResultMsg("F", "工程生成失败！");
        if (mark) {
            rmsg = new ResultMsg("T", "工程生成成功！");
        }
        return rmsg;
    }

    //生成jsp页面
    @RequestMapping(value = "createPage", method = "post")
    public ResultMsg createPage(HttpServletRequest request, HttpServletResponse response) {
        String pageId = request.getParameter("pageId");
        if (StrUtil.isNull(pageId)) {
            return new ResultMsg("F", "缺少方法参数");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> paramVo = new HashMap<String, Object>();
        paramVo.put("sysPageManager.w_pageId", pageId);
        paramVo.put("modelTypes", "s_sysPageManager");
        List<Map> list = (List) BuildProjectFactory.instance().init(paramVo);
        if (ToolsUtil.isEmpty(list)) {
            return new ResultMsg("F", "没有获取到定义的模板");
        }
        Map temp = list.get(0);
        map.put("template", temp);

        paramVo = new HashMap<String, Object>();
        paramVo.put("sysPageDetail.w_moduleId", pageId);
        paramVo.put("modelTypes", "s_sysPageDetail");
        paramVo.put("orderBy", "sysPageDetail.tab_no asc");
        List<Map> listDetial = (List) BuildProjectFactory.instance().init(paramVo);
        if (ToolsUtil.isEmpty(list)) {
            return new ResultMsg("F", "没有获取到定义的模板详情");
        }
        map.put("detail", listDetial);

        boolean mark = BuildProjectFactory.instance().ctreateProjects(map);
        ResultMsg rmsg = new ResultMsg("F", "工程生成失败！");
        if (mark) {
            rmsg = new ResultMsg("T", "工程生成成功！");
        }
        return rmsg;
    }

    @RequestMapping(value = "createPageContent", method = "post")
    public ResultMsg createPageContent(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> data = new HashMap<String, Object>();
        String pageId = request.getParameter("pageId");
        String databaseType = request.getParameter("databaseType");
        if (StrUtil.isNull(pageId)) {
            return new ResultMsg("F", "缺少方法参数");
        }

        Map<String, Object> paramVo = new HashMap<String, Object>();
        paramVo.put("sysPageManager.w_pageId", pageId);
        paramVo.put("modelTypes", "s_sysPageManager");
        List<DataMap> list = (List<DataMap>) BuildProjectFactory.instance().init(paramVo);
        if (ToolsUtil.isEmpty(list)) {
            return new ResultMsg("F", "没有获取到定义的模板");
        }
        DataMap sysPageManagerObj = list.get(0);
        String tableName=String.valueOf(sysPageManagerObj.get("mainObj"));
        data.put("sysPageManager", sysPageManagerObj);


        data.put("ctx", request.getContextPath());
        //查询数据表
        paramVo = new HashMap<String, Object>();
        paramVo.put("modelTypes", "s_sortInfo");
        paramVo.put("sortInfo.w_infoTableName", tableName);
        paramVo.put("datasource", "plateform");
        List<DataMap> sortInfoList = (List<DataMap>) CreateTableSql.instance().init(paramVo);
        if (sortInfoList == null || sortInfoList.size() < 1) {
            return new ResultMsg("F", "未找的表数据！");
        }
        log.info("查询出数据表 ->  ["+sortInfoList.size()+"]条记录！");
        DataMap sortInfoObj = sortInfoList.get(0);
        String sortId=String.valueOf(sortInfoObj.get("sortId"));
        data.put("sortInfo", sortInfoObj);

        //查询字段
        Map<String, Object> pubMetadataVo = new HashMap<String, Object>();
        pubMetadataVo.put("modelTypes", "s_metadata");
        pubMetadataVo.put("metadata.wi_sortId", sortId);
        String orderByVal = "";
        if("oracle".equalsIgnoreCase(databaseType)){
            orderByVal = "to_number(metadata.reserved1) asc";
        }else if ("mysql".equalsIgnoreCase(databaseType)){
            orderByVal = "cast(metadata.reserved1 as unsigned int) asc ";
        }
        pubMetadataVo.put("orderBy", orderByVal);
        pubMetadataVo.put("datasource", "plateform");
        List<DataMap> pubMetadataList = (List<DataMap>) CreateTableSql.instance().init(pubMetadataVo);
        log.info("查询出字段数 ->  ["+pubMetadataList.size()+"]条记录！");

        data.put("fieldListMap", pubMetadataList);

        boolean mark = BuildProjectFactory.instance().ctreateProjects(data);
        ResultMsg rmsg = new ResultMsg("F", "工程生成失败！");
        if (mark) {
            rmsg = new ResultMsg("T", "工程生成成功！");
        }
        return rmsg;
    }

    @RequestMapping(value = "buildSql", method = "post")
    public ResultMsg buildSql(HttpServletRequest request, HttpServletResponse response) {
        String databaseType = request.getParameter("databaseType");
        Map<String, String> params = new HashMap<String, String>();
        params.put("databaseType", databaseType);
        String sql = CreateTableSql.instance().createTable(params);
        ResultMsg msg = new ResultMsg("T", sql);
        return msg;
    }

    @RequestMapping(value = "buildMenu", method = "post")
    public ResultMsg buildLeftPage(HttpServletRequest request, HttpServletResponse response) {
        //common/工名/left-meuu.jsp
        String id = request.getParameter("id");
        if (Validator.isNull(id)) {
            ResultMsg msg = new ResultMsg("F", "请选择要生成的系统模块");
            return msg;
        }
        Map<String, Object> paramVo = new HashMap<String, Object>();
        paramVo.put("modelTypes", "s_sysModule");
        paramVo.put("sysModule.fatherId", id);
        String path = ToolsUtil.getInstance().getLocalByKey("config.properties","menu_path") + "/";
        List list = (List) CreateTableSql.instance().init(paramVo);
        if (Validator.isEmpty(list)) {
            ResultMsg msg = new ResultMsg("F", "没有获取到待生成数据");
            return msg;
        }
        int count = list.size();
        String nameStr = "";
        StringBuffer sb = new StringBuffer("<%@ page contentType=\"text/html;charset=UTF-8\" %>\n");
        sb.append("<ul class=\"sidebar-menu\">\n");
        for (int i = 0; i < count; i++) {
            Map map = (Map) list.get(i);
            sb.append("\n<li class=\"treeview\">\n<a href=\"javascript:void('0')\">\n");
            sb.append("<i class=\"fa fa-user\"></i> <span>" + map.get("title")
                    + "</span><i class=\"fa fa-angle-left pull-right\"></i>\n</a>\n");
            sb.append(createSubMenu(String.valueOf(map.get("moduleId"))));
            sb.append("\n</li>");
            if (Validator.isNull(nameStr))
                nameStr = String.valueOf(map.get("sysName"));
        }

        sb.append("\n</ul>");

        FileOperate.getInstance().newCreateFolder(path + "common/" + nameStr + "/");
        FileOperate.getInstance()
                .newCreateFile(path + "common/" + nameStr + "/left-menu.jsp", sb.toString());
        ResultMsg msg = new ResultMsg("T", "数据生成成功");
        return msg;
    }

    private String createSubMenu(String id) {
        StringBuffer sb = new StringBuffer();
        Map<String, Object> paramVo = new HashMap<String, Object>();
        paramVo.put("modelTypes", "s_sysModule");
        paramVo.put("sysModule.fatherId", id);
        List list = (List) CreateTableSql.instance().init(paramVo);
        if (Validator.isEmpty(list))
            return "";
        int count = list.size();
        sb.append("<ul class=\"treeview-menu\">\n");
        for (int i = 0; i < count; i++) {
            Map map = (Map) list.get(i);
            if ("T".equalsIgnoreCase(String.valueOf(map.get("ifLast")))) {
                String pageUrl = String.valueOf(map.get("pageUrl"));
                if (Validator.isNull(pageUrl)) {
                    sb.append("<li><i class=\"fa fa-circle-o\"></i>" + map.get("title")
                            + "</a></li>\n");
                } else {
                    String liIdDef = pageUrl
                            .substring(pageUrl.lastIndexOf("/") + 1, pageUrl.length() - 4);
                    String liId = StrUtil.doNull(String.valueOf(map.get("menuId")), liIdDef);
                    String gotoUrl = pageUrl.substring(0, pageUrl.length() - 4);
                    sb.append(
                            "<li id=\"" + liId + "\"><a href=\"${ctx}/sendPage/" + gotoUrl + "\">");
                    sb.append(
                            "<i class=\"fa fa-circle-o\"></i>" + map.get("title") + "</a></li>\n");
                }
            } else {
                sb.append(
                        "<li><i class=\"fa fa-circle-o\"></i>" + map.get("title") + "</a></li>\n");
                sb.append(createSubMenu(String.valueOf(map.get("moduleId"))));
            }
        }
        sb.append("</ul>");
        return sb.toString();
    }

    /**
     * 生成一级、二级菜单
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "buildCateMenu", method = "post")
    public ResultMsg buildCateLeftPage(HttpServletRequest request, HttpServletResponse response) {
        ResultMsg msg = new ResultMsg("F", "生成失败");
        String databaseType = StrUtil.doNull(request.getParameter("databaseType"),"oracle");
        try {
            //common/工名/left-meuu.jsp
            //String tempName = "menu-cate.inc";
            String sysModelId = request.getParameter("moduleId");
            Map<String, Object> data = new HashMap<String, Object>();
            Map<String, Object> paramVo = new HashMap<String, Object>();
            List list = null;
            String cateNo = request.getParameter("cateNo");
            String sysName = Validator.getDefaultStr(request.getParameter("sysName"), "plateform");
            String moduleType = Validator.getDefaultStr(request.getParameter("moduleType"), "2");
            String orderByVal = "";
            if("oracle".equalsIgnoreCase(databaseType)){
                orderByVal = "to_number(sysModule.num) asc,to_number(sysModule.order_no) asc nulls last ";
            }else if ("mysql".equalsIgnoreCase(databaseType)){
                orderByVal = "cast(sysModule.num as unsigned int) asc,cast(sysModule.order_no as unsigned int) asc";
            }
            if (StrUtil.isNull(sysModelId)) {
                String cateId = request.getParameter("cateId");
                String cateName = request.getParameter("cateName");

                if (Validator.isNull(cateId) && Validator.isNull(cateNo)) {
                    msg = new ResultMsg("F", "品种ID和品种编号不能为空！");
                    return msg;
                }
                data.put("cateName", cateName);
                data.put("cateNo", cateNo);
                data.put("sysName", sysName);

                paramVo.put("modelTypes", "s_sysModule");
                paramVo.put("sysModule.w_fatherId", cateId);
                paramVo.put("sysModule.w_ifShow", "T");
                paramVo.put("orderBy", orderByVal);

                list = (List) CreateTableSql.instance().init(paramVo);
                data.put("sysModuleList", list);
            } else {
                paramVo.put("modelTypes", "s_sysModule");
                paramVo.put("sysModule.w_moduleId", sysModelId);
                List parentlist = (List) CreateTableSql.instance().init(paramVo);
                Map map = (Map) parentlist.get(0);
                cateNo = String.valueOf(map.get("cateNo"));
                sysName = String.valueOf(map.get("sysName"));
                paramVo.remove("sysModule.w_moduleId");
                paramVo.put("sysModule.w_fatherId", map.get("moduleId"));
                paramVo.put("sysModule.w_ifShow", "T");
                paramVo.put("orderBy", orderByVal);
                list = (List) CreateTableSql.instance().init(paramVo);
                data.put("sysModuleList", list);
                data.put("cateNo", cateNo);
                data.put("sysName", sysName);
            }
            data.put("moduleType", moduleType);
            int count = list.size();
            //查询子表数据
            Map<String, Object> subMapData = new HashMap<String, Object>();
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    Map map = (Map) list.get(i);
                    String moduleId = String.valueOf(map.get("moduleId"));
                    Map<String, Object> paramChilVo = new HashMap<String, Object>();
                    paramChilVo.put("modelTypes", "s_sysModule");
                    paramChilVo.put("sysModule.fatherId", moduleId);
                    paramChilVo.put("sysModule.w_ifShow", "T");
                    paramChilVo.put("orderBy",orderByVal);
                    List listChil = (List) CreateTableSql.instance().init(paramChilVo);
                    subMapData.put("sub-" + moduleId, listChil);
                }
            }
            data.put("sysSubList", subMapData);

            String path = ToolsUtil.getInstance().getLocalByKey("config.properties","menu_path") + "/";//根目录

            //admin的left左侧菜单
            String templateLeft = "plateform/project/admin-left-menu-cate.inc";
            String leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftContent = leftContent.replace("###", "$");
            String leftJsp = path + "common/" + sysName + "/left-menu-" + cateNo + ".jsp";
            FileOperate.getInstance().newCreateFolder(path + "common/" + sysName + "/");
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            //admin的主体index页面
            /**
             String templateIndex = "coding/pages/admi/WEB-INF/templatecoding/pages/;
             String indexContent = FreemarkerHelper.instance().getTemplateStr(templateIndex, data);
             indexContent = indexContent.replace("###", "$");
             String indexJsp = path + "WEB-INF/pages/" + sysName + "/admin/" + "/index-" + cateNo + ".jsp";
             FileOperate.getInstance().newCreateFile(indexJsp, indexContent);
             **/
            msg = new ResultMsg("T", "页面生成完成");
        } catch (Exception e) {
            e.printStackTrace();
            msg = new ResultMsg("F", "生成失败");
        }
        return msg;
    }

    //创建web工程
    @RequestMapping(value = "createProject", method = "post")
    public ResultMsg createProject(HttpServletRequest request, HttpServletResponse response) {
        String path = ToolsUtil.getInstance().getLocalByKey("config.properties","menu_path") + "/";//根目录
        ResultMsg msg = new ResultMsg("F", "Web工程创建失败");
        String sysEname = request.getParameter("sysEname");
        String sysCname = request.getParameter("sysCname");
        String sysColor = request.getParameter("sysColor");
        String userCenterFlag = StrUtil.doNull(request.getParameter("userCenterFlag"),"F");
        String userCenterColor = StrUtil.doNull(request.getParameter("userCenterColor"),"");
        if (Validator.isNull(sysEname)) {
            return new ResultMsg("F", "请选择需要生成工程的系统");
        }
        String project_root_path =  ToolsUtil.getInstance().getLocalByKey("config.properties", "project_root_path");
        if(!StrUtil.isNull(project_root_path)){
            path = project_root_path + sysEname + "-server/src/main/resources/META-INF/resources/";
        }
        log.info("-");
        log.info("文件创建根目录："+path);

//        File file = new File(path + "common/" + sysEname + "/left.jsp");
//        if (file.exists()) {
//            log.info("文件["+file.getPath()+"]已存在，不能重复创建："+file.getPath());
//            return new ResultMsg("F", "此工程["+sysEname+"]存在，不能重复创建");
//        }
        log.info("开始创建Web工程： "+sysEname+" -> "+sysCname);
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("sysEname", sysEname);
            data.put("sysCname", sysCname);
            data.put("sysColor", StrUtil.doNull(sysColor,"skin-blue"));
            data.put("userCenterFlag", userCenterFlag);
            data.put("userCenterColor", StrUtil.doNull(userCenterColor,"skin-green-light"));
            String templateLeft = "plateform/project/admin-index.inc";
            String leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            String leftJsp = path + "WEB-INF/pages/" + sysEname + "/admin/index.jsp";
            FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/admin");
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            //			templateLeft = "coding/pages/platef/WEB-INF/template/coding/pages/x.inc";
            //			leftContent = FreemarkerHelper.instance().getTemplateStr(templateLeft, data);
            //			leftJsp = path + "/WEB-INF/pages/" + sysEname + "/web/index.jsp";
            //			FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            //以下是公用资源
            templateLeft = "plateform/project/admin-top.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "/common/" + sysEname + "/top.jsp";
            FileOperate.getInstance().newCreateFolder(path + "/common/" + sysEname);
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            templateLeft = "plateform/project/admin-foot.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "common/" + sysEname + "/foot.jsp";
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            templateLeft = "plateform/project/admin-left.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "common/" + sysEname + "/left.jsp";
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            templateLeft = "plateform/project/admin-left-menu.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "common/" + sysEname + "/left-menu.jsp";
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            templateLeft = "plateform/project/common-base.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "common/" + sysEname + "/include/common-base.jsp";
            FileOperate.getInstance().newCreateFolder(path + "common/" + sysEname + "/include");
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            templateLeft = "plateform/project/mystyle.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "common/" + sysEname + "/base/utils/mystyle.css";
            FileOperate.getInstance().newCreateFolder(path + "common/" + sysEname + "/base/utils");
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            templateLeft = "plateform/project/mytools.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "common/" + sysEname + "/base/utils/mytools.js";
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            templateLeft = "plateform/project/admin-login.inc";
            leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
            leftJsp = path + "login.jsp";
            FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

            //以下是用户中心
            if(StrUtil.isNotNull(userCenterFlag) && "T".equals(userCenterFlag)){
                templateLeft = "plateform/project/user-top.inc";
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "common/" + sysEname + "/top-user.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-left.inc";
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "common/" + sysEname + "/left-user.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-foot.inc";
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "common/" + sysEname + "/foot-user.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-index.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/user");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/user/index.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-loading.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/user");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/user/loading.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                //templateLeft = "plateform/project/user-loading.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/pro");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/pro/pro-view.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-loginIndex.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/user");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/loginIndex.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-reg-index.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/reg");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/reg/reg-index.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-my-user-edit-pass.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/user");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/user/my-user-edit-pass.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-my-message.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/user");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/user/my-message.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);

                templateLeft = "plateform/project/user-my-collection.inc";
                FileOperate.getInstance().newCreateFolder(path + "WEB-INF/pages/" + sysEname + "/web/user");
                leftContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateLeft);
                leftJsp = path + "WEB-INF/pages/" + sysEname + "/web/user/my-collection.jsp";
                FileOperate.getInstance().newCreateFile(leftJsp, leftContent);
            }
            log.info("-");
            return new ResultMsg("T", "Web工程["+sysEname+"]创建成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 发布站点（根据模板temp生成站点首页等相关html）
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "createWebSite", method = "post")
    public Object createWebSite(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "生成失败");
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("ctx", request.getContextPath());
            String sysName = Validator.getDefaultStr(request.getParameter("sysName"), "cms");

            //1、获取参数
            String siteCode = request.getParameter("siteCode");
            String siteId = request.getParameter("siteId");
            if (Validator.isNull(siteId) && Validator.isNull(siteCode)) {
                resultMap.put("msg", "站点代号或者站点ID必须有一个不为空！");
                return resultMap;

            }
            //2、获取当前站点对象及数据
            Map<String, Object> paramVoSite = new HashMap<String, Object>();
            paramVoSite.put("modelTypes", "s_tWebsite");
            paramVoSite.put("datasource", sysName);
            if (Validator.isNotNull(siteCode)) {
                paramVoSite.put("tWebsite.w_siteCode", siteCode);
            }
            if (Validator.isNotNull(siteId)) {
                paramVoSite.put("tWebsite.w_siteId", siteId);
            }
            List webSiteList = (List) CreateTableSql.instance().init(paramVoSite);
            if (webSiteList == null || webSiteList.size() < 1) {
                resultMap.put("msg", "未找到对应站点！");
                return resultMap;
            }
            Map<String, Object> webSiteData = new HashMap<String, Object>();
            webSiteData = (Map) webSiteList.get(0);

            String temp_top = Validator
                    .getDefaultStr(String.valueOf(webSiteData.get("tempTop")), "/top.inc");
            String temp_common = Validator
                    .getDefaultStr(String.valueOf(webSiteData.get("tempCom")), "/common.inc");
            String temp_index = Validator
                    .getDefaultStr(String.valueOf(webSiteData.get("tempIndex")), "/index.inc");
            String temp_bottom = Validator
                    .getDefaultStr(String.valueOf(webSiteData.get("tempBott")), "/bottom.inc");
            //			String temp_data = Validator.getDefaultStr(String.valueOf(webSiteData.get("tempData")),
            //					"/tools-index-data.inc");

            data.put("site", webSiteData);

            //3、获取此站点下面的所有栏目（多层级的）

            Map<String, Object> paramVo = new HashMap<String, Object>();
            paramVo.put("modelTypes", "s_tChannel");
            paramVo.put("datasource", sysName);
            if (Validator.isNotNull(siteCode)) {
                paramVo.put("tChannel.w_siteCode", siteCode);
            }
            if (Validator.isNotNull(siteId)) {
                paramVo.put("tChannel.w_siteId", siteId);
            }
            paramVo.put("tChannel.w_status", "1");
            //			paramVo.put("tChannel.w_isNavigation", "1");
            paramVo.put("orderBy", "channel_levels asc");

            List channelList = (List) CreateTableSql.instance().init(paramVo);
            Map<String, Object> channelData = new HashMap<String, Object>();
            int count = channelList.size();
            data.put("channelList", channelList);

            List firstList = new ArrayList();
            List childList = new ArrayList();

            Map<String, Object> childListMap = new HashMap<String, Object>();
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    Map map = (Map) channelList.get(i);
                    String channelCode = String.valueOf(map.get("codeName"));
                    String channelId = String.valueOf(map.get("channelId"));
                    String parentId = String.valueOf(map.get("parentId"));
                    String isNavigation = String.valueOf(map.get("isNavigation"));
                    if (parentId.equals("0") && isNavigation.equals("1")) {
                        firstList.add(map);//一级栏目
                    } else {
                        if("1".equals(isNavigation)){//是导航
                            List secList = new ArrayList();
                            if (childListMap.containsKey(parentId)) {
                                secList = (List) childListMap.get(parentId);
                            }
                            secList.add(map);
                            childListMap.put(parentId, secList);
                        }
                    }
                }
            }

            data.put("firstList", firstList);
            data.put("childList", childListMap);

            String path = ToolsUtil.getInstance().getLocalByKey("config.properties","html_path") + "/";
            //D:/Workspaces/portal-web/WebRoot/wcm

            String htmlRoot = path + siteCode + "/html/";
            if(!FileOperate.getInstance().checkFolder(htmlRoot)){
                FileOperate.getInstance().newCreateFolder(htmlRoot);//创建站点下 html 文件夹
            }
            String dataRoot = path + siteCode + "/data/";
            if(!FileOperate.getInstance().checkFolder(dataRoot)){
                FileOperate.getInstance().newCreateFolder(dataRoot);//创建站点下 data 文件夹
            }

            //1、生成公用导航top.html文件
            String html_top = htmlRoot + "/top.html";
            temp_top = siteCode + "/template/" + temp_top;
            String content_top = FreemarkerHelper.instance().getTemplateStr(data, temp_top, "web");
            boolean flag_top = FileOperate.getInstance().newCreateFile(html_top, content_top);
            log.info("使用模板[" + temp_top + "]生成[" + html_top + "] " + flag_top);

            //2、生成公用common.html文件
            String html_common = htmlRoot + "/common.js";
            temp_common = siteCode + "/template/" + temp_common;
            String content_common = FreemarkerHelper.instance()
                    .getTemplateStr(data, temp_common, "web");
            boolean flag_common = FileOperate.getInstance()
                    .newCreateFile(html_common, content_common);
            log.info("使用模板[" + temp_common + "]生成[" + html_common + "] " + flag_common);

            //3、生成公用bottom.html文件
            String html_bottom = htmlRoot + "/bottom.html";
            temp_bottom = siteCode + "/template/" + temp_bottom;
            String content_bottom = FreemarkerHelper.instance()
                    .getTemplateStr(data, temp_bottom, "web");
            boolean flag_bottom = FileOperate.getInstance()
                    .newCreateFile(html_bottom, content_bottom);
            log.info("使用模板[" + temp_bottom + "]生成[" + html_bottom + "] " + flag_bottom);

            //生成网站首页index.html文件
            String html_index = htmlRoot + "/index.html";
            temp_index = siteCode + "/template/" + temp_index;
            String content_index = FreemarkerHelper.instance()
                    .getTemplateStr(data, temp_index, "web");
            boolean flag_index = FileOperate.getInstance().newCreateFile(html_index, content_index);
            log.info("使用模板[" + temp_index + "]生成[" + html_index + "] " + flag_index);

            //生成网站首页预览index-preview.html文件
            String html_index_preview = htmlRoot + "/index-preview.html";
            String content_index_preview = FreemarkerHelper.instance()
                    .getTemplateStr(data, temp_index, "web");
            content_index_preview += "<div id=\"template-preview-box\"></div>\n<script>$.ajaxSetup ({cache: false});$(\"#template-preview-box\").load(\"/common/base/tools-index-preview.html?f=\"+new Date().getTime());</script>";
            boolean flag_index_preview = FileOperate.getInstance()
                    .newCreateFile(html_index_preview, content_index_preview);
            log.info("使用模板[" + temp_index + "]生成[" + html_index_preview + "] " + flag_index_preview);

            //			//生成tools-index-data.js文件
            //			String html_data = htmlRoot + "/tools-index-data.js";
            //			temp_data = "template"+temp_data;
            //			String content_data = FreemarkerHelper.instance().getTemplateStr(data, temp_data, "web");
            //			boolean flag_data = FileOperate.getInstance().newCreateFile(html_data, content_data);
            //			log.info("使用模板[" + temp_data + "]生成[" + html_data + "] " + flag_data);

            resultMap.put("flag", "T");
            resultMap.put("msg", "网站结构生成完成！");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("msg", e.getMessage());
        }
        return resultMap;
    }
    /**
     * 重新生成栏目导航top.html（根据模板temp生成站点栏目top.html）
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "createWebSiteChannel", method = "post")
    public Object createWebSiteChannel(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "生成失败");
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("ctx", request.getContextPath());
            String sysName = Validator.getDefaultStr(request.getParameter("sysName"), "cms");

            //1、获取参数
            String siteCode = request.getParameter("siteCode");
            String siteId = request.getParameter("siteId");
            if (Validator.isNull(siteId) && Validator.isNull(siteCode)) {
                resultMap.put("msg", "站点代号或者站点ID必须有一个不为空！");
                return resultMap;

            }
            //2、获取当前站点对象及数据
            Map<String, Object> paramVoSite = new HashMap<String, Object>();
            paramVoSite.put("modelTypes", "s_tWebsite");
            paramVoSite.put("datasource", sysName);
            if (Validator.isNotNull(siteCode)) {
                paramVoSite.put("tWebsite.w_siteCode", siteCode);
            }
            if (Validator.isNotNull(siteId)) {
                paramVoSite.put("tWebsite.w_siteId", siteId);
            }
            List webSiteList = (List) CreateTableSql.instance().init(paramVoSite);
            if (webSiteList == null || webSiteList.size() < 1) {
                resultMap.put("msg", "未找到对应站点！");
                return resultMap;
            }
            Map<String, Object> webSiteData = new HashMap<String, Object>();
            webSiteData = (Map) webSiteList.get(0);
            //获取top.inc模板
            String temp_top = Validator
                    .getDefaultStr(String.valueOf(webSiteData.get("tempTop")), "/top.inc");
            data.put("site", webSiteData);
            //3、获取此站点下面的所有栏目（多层级的）
            Map<String, Object> paramVo = new HashMap<String, Object>();
            paramVo.put("modelTypes", "s_tChannel");
            paramVo.put("datasource", sysName);
            if (Validator.isNotNull(siteCode)) {
                paramVo.put("tChannel.w_siteCode", siteCode);
            }
            if (Validator.isNotNull(siteId)) {
                paramVo.put("tChannel.w_siteId", siteId);
            }
            paramVo.put("tChannel.w_status", "1");
            //			paramVo.put("tChannel.w_isNavigation", "1");
            paramVo.put("orderBy", "channel_levels asc");

            List channelList = (List) CreateTableSql.instance().init(paramVo);
            Map<String, Object> channelData = new HashMap<String, Object>();
            int count = channelList.size();
            data.put("channelList", channelList);

            List firstList = new ArrayList();
//            List childList = new ArrayList();
            Map<String, Object> childListMap = new HashMap<String, Object>();
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    Map map = (Map) channelList.get(i);
                    String channelCode = String.valueOf(map.get("codeName"));
                    String channelId = String.valueOf(map.get("channelId"));
                    String parentId = String.valueOf(map.get("parentId"));
                    String isNavigation = String.valueOf(map.get("isNavigation"));
                    if (parentId.equals("0") && isNavigation.equals("1")) {
                        firstList.add(map);//一级栏目
                    } else {
                        if("1".equals(isNavigation)){//是导航
                            List secList = new ArrayList();
                            if (childListMap.containsKey(parentId)) {
                                secList = (List) childListMap.get(parentId);
                            }
                            secList.add(map);
                            childListMap.put(parentId, secList);
                        }
                    }
                }
            }
            data.put("firstList", firstList);
            data.put("childList", childListMap);

            String path = ToolsUtil.getInstance().getLocalByKey("config.properties","html_path") + "/";
            //D:/Workspaces/portal-web/WebRoot/wcm

            String htmlRoot = path + siteCode + "/html/";
            if(!FileOperate.getInstance().checkFolder(htmlRoot)){
                FileOperate.getInstance().newCreateFolder(htmlRoot);//创建站点下 html 文件夹
            }
            //1、生成公用导航top.html文件
            String html_top = htmlRoot + "/top.html";
            temp_top = siteCode + "/template/" + temp_top;
            String content_top = FreemarkerHelper.instance().getTemplateStr(data, temp_top, "web");
            boolean flag_top = FileOperate.getInstance().newCreateFile(html_top, content_top);
            log.info("使用模板[" + temp_top + "]生成[" + html_top + "] " + flag_top);

            resultMap.put("flag", "T");
            resultMap.put("msg", "网站栏目生成完成！");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("msg", e.getMessage());
        }
        return resultMap;
    }
    /**
     * 发布生成栏目 （根据模板temp生成栏目首页等相关html）
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "createWebChannel", method = "post")
    public ResultMsg createWebChannel(HttpServletRequest request, HttpServletResponse response) {
        ResultMsg msg = new ResultMsg("F", "生成失败");
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("ctx", request.getContextPath());

            //1、获取参数
            String channelId = request.getParameter("channelId");
            if (Validator.isNull(channelId)) {
                return new ResultMsg("F", "栏目标识不能为空！");
            }

            //2、获取此站点下面的所有栏目（多层级的）
            Map<String, Object> paramVo = new HashMap<String, Object>();
            paramVo.put("modelTypes", "s_tChannel");
            paramVo.put("tChannel.w_channelId", channelId);
            String sysName = Validator.getDefaultStr(request.getParameter("sysName"), "cms");
            paramVo.put("datasource", sysName);

            List channelList = (List) CreateTableSql.instance().init(paramVo);
            if (channelList == null || channelList.size() < 1) {
                return new ResultMsg("F", "未找的栏目数据！");
            }

            Map<String, Object> channelData = new HashMap<String, Object>();
            channelData = (Map) channelList.get(0);
            data.put("channel", channelData);

            String siteId = String.valueOf(channelData.get("siteId"));
            String siteCode = String.valueOf(channelData.get("siteCode"));
            String channelCode = String.valueOf(channelData.get("codeName"));
            String tempList = String.valueOf(channelData.get("tempList"));
            String parentId = String.valueOf(channelData.get("parentId"));
            String redirectUrl = String.valueOf(channelData.get("redirectUrl"));

            if (!"0".equals(parentId)) {
                //3、获取当前栏目同级兄弟栏目brother
                Map<String, Object> brotherChannelVo = new HashMap<String, Object>();
                brotherChannelVo.put("modelTypes", "s_tChannel");
                brotherChannelVo.put("tChannel.w_parentId", parentId);
                brotherChannelVo.put("tChannel.w_status", "1");
                brotherChannelVo.put("orderBy", "channel_levels");
                brotherChannelVo.put("datasource", sysName);
                List brotherChannelList = (List) CreateTableSql.instance().init(brotherChannelVo);
                if (brotherChannelList == null || brotherChannelList.size() < 1) {
                    log.info("未找该栏目的兄弟栏目数据！");
                }
                data.put("brotherChannelList", brotherChannelList);

                //3.获取当前栏目父级栏目
//                Map<String, Object> fatherChannelVo = new HashMap<String, Object>();
//                fatherChannelVo.put("modelTypes", "s_tChannel");
//                fatherChannelVo.put("tChannel.w_channelId", parentId);
//                fatherChannelVo.put("datasource", sysName);
//                List fatherChannelList = (List) CreateTableSql.instance().init(fatherChannelVo);
//                if (fatherChannelList == null || fatherChannelList.size() < 1) {
//                    return new ResultMsg("F", "未找的父级栏目数据！");
//                }
//                Map<String, Object> fatherChannelData = new HashMap<String, Object>();
//                fatherChannelData = (Map) fatherChannelList.get(0);
//                data.put("fatherChannel", fatherChannelData);

                //递归获取各父级栏目树
                getFatherChannelData(data,parentId, sysName);

            }

            //获取当前栏目下属1层子级栏目数据
            Map<String, Object> childChannelVo = new HashMap<String, Object>();
            childChannelVo.put("modelTypes", "s_tChannel");
            childChannelVo.put("tChannel.w_parentId", channelId);
            childChannelVo.put("datasource", sysName);
            List childChannelList = (List) CreateTableSql.instance().init(childChannelVo);
            if (childChannelList == null || childChannelList.size() < 1) {
                log.info("未找该栏目的子栏目数据！");
            }
            data.put("childChannelList", childChannelList);

            //4、获取当前栏目所属站点对象及数据
            Map<String, Object> paramVoSite = new HashMap<String, Object>();
            paramVoSite.put("modelTypes", "s_tWebsite");
            paramVoSite.put("tWebsite.w_siteId", siteId);
            paramVoSite.put("datasource", sysName);
            List webSiteList = (List) CreateTableSql.instance().init(paramVoSite);
            if (webSiteList == null || webSiteList.size() < 1) {
                return new ResultMsg("F", "未找到对应站点");
            }
            Map<String, Object> webSiteData = new HashMap<String, Object>();
            webSiteData = (Map) webSiteList.get(0);
            data.put("site", webSiteData);

            log.info("栏目相关数据："+JSONObject.fromObject(data));

            //5、生成栏目目录
            String path = ToolsUtil.getInstance().getLocalByKey("config.properties","html_path") + "/";//D:/Workspaces/portal-web/WebRoot/wcm

//            String htmlRoot = path + siteCode + "/html/";
//            if(!FileOperate.getInstance().checkFolder(htmlRoot)){
//                FileOperate.getInstance().newCreateFolder(htmlRoot);//创建站点下 html 文件夹
//            }
            String channelRoot = path + siteCode+redirectUrl;
            channelRoot = channelRoot.substring(0,channelRoot.lastIndexOf("/"));
            if(!FileOperate.getInstance().checkFolder(channelRoot)){
                FileOperate.getInstance().newCreateFolder(channelRoot);//创建站点下 channel 文件夹
                boolean fte = FileOperate.getInstance().newCreateFolder(channelRoot);
                log.info("------ folder creation completed:" + channelRoot + " return " + fte);
            }

            //3、生成栏目首页index.html（一般是二级列表页）
//            String html = channelRoot + "/index.html";
            String html=path + siteCode+redirectUrl;

            String temp = siteCode + "/template/" + tempList;
            String content_top = FreemarkerHelper.instance().getTemplateStr(data, temp, "web");
            boolean flag = FileOperate.getInstance().newCreateFile(html, content_top);
            log.info("使用模板[" + temp + "]生成[" + html + "] " + flag);

            String filePath = ToolsUtil.getInstance().getLocalByKey("config.properties", "html_path") + "/";
            String defStr = filePath + siteCode + "/data/";
            FileOperateUtil.newCreateFolder(defStr);
            String fileName = defStr +"channel_index_"+channelCode+ ".json";
            boolean returnFalg = FileOperateUtil.newCreateFile(fileName, JSONObject.fromObject(data).toString(),
                            "UTF-8");
            log.info("栏目相关数据文件生成：" + fileName + "   |   " + returnFalg);

            msg = new ResultMsg("T", "栏目发布完成");
        } catch (Exception e) {
            e.printStackTrace();
            msg = new ResultMsg("F", "栏目发布失败");
        }
        return msg;
    }

    //获取父栏目节点信息（支持多层父级）
    private Map<String, Object> getFatherChannelData(Map<String, Object> dataRes,String parentId,String sysName){
        Map<String, Object> fatherChannelVo = new HashMap<String, Object>();

        Map<String, Object> fatherObj = new HashMap<String, Object>();
        fatherChannelVo.put("modelTypes", "s_tChannel");
        fatherChannelVo.put("tChannel.w_channelId", parentId);
        fatherChannelVo.put("datasource", sysName);
        List fatherChannelList = (List) CreateTableSql.instance().init(fatherChannelVo);
        if (fatherChannelList != null && fatherChannelList.size() >0) {
            DataMap obj = (DataMap) fatherChannelList.get(0);
            fatherObj.putAll(obj);
            if(fatherObj!=null && fatherObj.size()>0){
                String father_parentId=String.valueOf(fatherObj.get("parentId"));
                if(!"0".equals(father_parentId)){
                    getFatherChannelData(fatherObj,father_parentId,sysName);
                }
            }
        }
        dataRes.put("fatherChannel", fatherObj);

        return dataRes;
    }

    //创建服务端server工程
    @RequestMapping(value = "createServerProject", method = "post")
    public ResultMsg createServerProject(HttpServletRequest request, HttpServletResponse response) {
        String localFileName = "config.properties";
        ResultMsg msg = new ResultMsg("F", "Server工程创建失败");
        String sysEname = request.getParameter("sysEname");
        if (Validator.isNull(sysEname)) {
            return new ResultMsg("F", "请选择需要生成工程的系统");
        }
        String downFlag = StrUtil.doNull(request.getParameter("downFlag"),"T");//默认提供下载
        boolean isDown = ("T".equals(downFlag)?true:false);

        String project_root_path =  ToolsUtil.getInstance().getLocalByKey(localFileName, "project_root_path");
        String fileUploadDirectory="",fileDownloadUrl="",path="",downRoot="";
        if(isDown){
            fileUploadDirectory  =  ToolsUtil.getInstance().getLocalByKey(localFileName, "UPLOAD_DIRECTORY");//获取文件需要上传到的根目录
            fileDownloadUrl =  ToolsUtil.getInstance().getLocalByKey(localFileName, "DOWNLOAD_URL");//获取文件需要下载的根目录地址
            path = fileUploadDirectory+"/project/";
            downRoot = fileDownloadUrl+"/project/";
        }else{
            if(StrUtil.isNull(project_root_path)){
                File directory = new File("");// 参数为空
                try {
                    project_root_path = directory.getCanonicalPath()+"/"+sysEname+"/";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            path=project_root_path;
        }

        String rootPath = StrUtil.doNull(request.getParameter("rootPath"),path);
        String serverIp = StrUtil.doNull(request.getParameter("serverIp"),"127.0.0.1");
        String serverPort = StrUtil.doNull(request.getParameter("serverPort"),"8080");
        String socketPort = StrUtil.doNull(request.getParameter("socketPort"),"8003");
        String ajpPort = StrUtil.doNull(request.getParameter("ajpPort"),getDefaultAjpPort(socketPort));

//        String dataType = StrUtil.doNull(request.getParameter("databaseType"),"mysql");
//        String driverClassName = StrUtil.doNull(request.getParameter("driverClassName"),"com.mysql.jdbc.Driver");
//        String jdbcUrl = StrUtil.doNull(request.getParameter("jdbcUrl"),"jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true");
//        String jdbcUserName = StrUtil.doNull(request.getParameter("jdbcUsername"),"ius_base");
//        String jdbcUserPass = StrUtil.doNull(request.getParameter("jdbcPassword"),"ius_base");

        String serverName = sysEname+"-server";//工程名称
        String serverRootPath = path + serverName;
        log.info("-");
        log.info("项目工程存放根目录："+rootPath);
        log.info("开始创建Server工程： "+sysEname+" -> "+serverRootPath);

        try {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("sysEname", sysEname);
            data.put("serverIp", serverIp);
            data.put("serverPort", serverPort);
            data.put("socketPort", socketPort);
            data.put("ajpPort", ajpPort);
            data.put("rootPath",project_root_path);
            data.putAll(getDefaultMinServiceConfig());

//            data.put("dataType", dataType);
//            data.put("driverClassName", driverClassName);
//            data.put("jdbcUrl", jdbcUrl);
//            data.put("jdbcUserName", jdbcUserName);
//            data.put("jdbcUserPass", jdbcUserPass);
            log.info("各个参数值："+data);

            FileOperate.getInstance().newCreateFolder(serverRootPath);
            String fileRootPath = "";
            String templateFile = "plateform/project-server/pom.ftl";
            String fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);
            String filePath = serverRootPath + "/pom.xml";
            FileOperate.getInstance().newCreateFile(filePath, fileContent);


            //创建resources目录
            fileRootPath="/src/main/resources";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录

            templateFile = "plateform/project-server"+fileRootPath+"/application.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/application.properties";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server"+fileRootPath+"/cache-conf.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/cache-conf.properties";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server"+fileRootPath+"/logback-spring.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/logback-spring.xml";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server"+fileRootPath+"/spring-context.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/spring-context.xml";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            //创建resources/config目录
            fileRootPath="/src/main/resources/config";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录
            templateFile = "plateform/project-server"+fileRootPath+"/readme.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/readme.txt";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server"+fileRootPath+"/config.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/config.properties";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server"+fileRootPath+"/keyword.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/keyword.properties";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            //创建resources/redis目录
            fileRootPath="/src/main/resources/redis";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录
            templateFile = "plateform/project-server"+fileRootPath+"/redis-config.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/redis-config.properties";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            //创建resources/spring目录
            fileRootPath="/src/main/resources/spring";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录
            templateFile = "plateform/project-server"+fileRootPath+"/applicationContext-sys.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/applicationContext-"+sysEname+".xml";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录
            templateFile = "plateform/project-server"+fileRootPath+"/datasource-config.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/datasource-config.xml";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            fileRootPath="/src/main/java/com/"+sysEname+"/controller";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);
            templateFile = "plateform/project-server/src/main/java/com/sysname/controller/TransAction.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/TransAction.java";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server/src/main/java/com/sysname/controller/IndexAction.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/IndexAction.java";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server/src/main/java/com/sysname/controller/ApiAction.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/ApiAction.java";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            fileRootPath="/src/main/java/com/"+sysEname+"/plugins";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);
            templateFile = "plateform/project-server/src/main/java/com/sysname/plugins/TestPluginImpl.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/TestPluginImpl.java";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            fileRootPath="/src/main/java/com";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录


            templateFile = "plateform/project-server"+fileRootPath+"/sysServerApplication.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/"+sysEname+"ServerApplication.java";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件


            fileRootPath="/src/main/java/com/apache/tomcat";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录

            templateFile = "plateform/project-server"+fileRootPath+"/FilterConfiguration.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/FilterConfiguration.java";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            templateFile = "plateform/project-server"+fileRootPath+"/WebServerConfiguration.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/WebServerConfiguration.java";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            //创建bin目录
            fileRootPath="/src/main/bin";
            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录
            templateFile = "plateform/project-server"+fileRootPath+"/start-bat.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/start.bat";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件

            FileOperate.getInstance().newCreateFolder(serverRootPath + fileRootPath);//创建文件目录
            templateFile = "plateform/project-server"+fileRootPath+"/start-sh.ftl";//模板地址
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);//读取模板内容
            filePath = serverRootPath + fileRootPath + "/start.sh";//指定生成的文件名称
            FileOperate.getInstance().newCreateFile(filePath, fileContent);//创建文件


            log.info("工程["+serverName+"]创建成功，开始压缩文件...");
            String zipPath =serverRootPath + ".zip";
            Map<String,String> reultMap = FileZipUtil.fileToZip(serverRootPath,zipPath);
            log.info("对文件压缩的结果："+reultMap);
            String zipRootPath = reultMap.get("fileNameNew");
            log.info("压缩文件存放位置："+zipRootPath);

            if(isDown){
                String downLoadPath=downRoot+serverName+".zip";
                log.info("压缩文件下载地址："+downLoadPath);
                return new ResultMsg("T", downLoadPath);
            }else{
                return new ResultMsg("T", "工程["+serverName+"]创建成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 生成数据库设计文档 （根据模板temp生成doc）
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "createDataBaseDoc", method = "post")
    public ResultMsg createDataBaseDoc(HttpServletRequest request, HttpServletResponse response) {
        log.info("生成数据库设计文档开始.......................");
        String databaseType = StrUtil.doNull(request.getParameter("databaseType"),"mysql");
        String sysEname = request.getParameter("sysEname");
        log.info("请求参数：databaseType="+databaseType+",sysEname="+sysEname);
        String localFileName = "config.properties";
        String fileUploadDirectory =  ToolsUtil.getInstance().getLocalByKey(localFileName, "UPLOAD_DIRECTORY");//获取文件需要上传到的根目录
        String fileDownloadUrl =  ToolsUtil.getInstance().getLocalByKey(localFileName, "DOWNLOAD_URL");//获取文件需要下载的根目录地址
        String nowDataStr = new SimpleDateFormat("yyyyMMdd").format(new Date());// + "/";
        String createFileRoot = fileUploadDirectory+"/atta/" +sysEname+"/"+ nowDataStr;// 创建文件的目录

        ResultMsg msg = new ResultMsg("F", "生成失败");
        JSONObject msgJson = new JSONObject();
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("ctx", request.getContextPath());
            data.put("databaseType",databaseType);

            //1、获取参数
            if (Validator.isNull(sysEname)) {
                return new ResultMsg("F", "系统标识不能为空");
            }

            //2、获取此系统下所有动态设计的表对象
            log.info("正在查询系统："+sysEname);
            Map<String, Object> sysVo = new HashMap<String, Object>();
            sysVo.put("modelTypes", "s_uctSys");
            sysVo.put("uctSys.w_sysEname", sysEname);
            sysVo.put("datasource", "plateform");
            List<DataMap> sysList = (List<DataMap>) CreateTableSql.instance().init(sysVo);
            if (sysList == null || sysList.size() < 1) {
                return new ResultMsg("F", "系统标识["+sysEname+"]不在存在！");
            }
            DataMap sysObj = sysList.get(0);
            String sysCname = String.valueOf(sysObj.get("sysCname"));
            log.info("系统对应名称："+sysCname);
            data.put("sysObj",sysObj);
            data.put("createMonth",new SimpleDateFormat("yyyy年MM月").format(new Date()));
            data.put("createDay",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

            //查询数据表
            Map<String, Object> paramVo = new HashMap<String, Object>();
            paramVo.put("modelTypes", "s_sortInfo");
            paramVo.put("sortInfo.w_sysName", sysEname);
            paramVo.put("orderBy", "sortInfo.info_table_name asc");
            paramVo.put("datasource", "plateform");
            List<DataMap> sortInfoList = (List<DataMap>) CreateTableSql.instance().init(paramVo);
            if (sortInfoList == null || sortInfoList.size() < 1) {
                return new ResultMsg("F", "未找的表数据！");
            }
            log.info("查询出数据表 ->  ["+sortInfoList.size()+"]条记录！");
            data.put("tableList",sortInfoList);

            String sortIdStr = "";
            Map<String,DataMap> sortMap = new HashMap<String,DataMap>();
            for(DataMap sortInfoObj : sortInfoList){
                String sortId = String.valueOf(sortInfoObj.get("sortId"));
                sortIdStr+=sortId+",";
                sortMap.put(sortId,sortInfoObj);
            }
            //查询字段
            sortIdStr = sortIdStr.substring(0,sortIdStr.length()-1);
            Map<String, Object> pubMetadataVo = new HashMap<String, Object>();
            pubMetadataVo.put("modelTypes", "s_metadata");
            pubMetadataVo.put("metadata.wi_sortId", sortIdStr);
            String orderByVal = "";
            if("oracle".equalsIgnoreCase(databaseType)){
                orderByVal = "to_number(metadata.reserved1) asc";
            }else if ("mysql".equalsIgnoreCase(databaseType)){
                orderByVal = "cast(metadata.reserved1 as unsigned int) asc ";
            }
            pubMetadataVo.put("orderBy", orderByVal);
            pubMetadataVo.put("datasource", "plateform");
            List<DataMap> pubMetadataList = (List<DataMap>) CreateTableSql.instance().init(pubMetadataVo);
            log.info("查询出字段数 ->  ["+pubMetadataList.size()+"]条记录！");

            //根据表整理完成
            Map<String,List<DataMap>> fieldListMap = new HashMap<String,List<DataMap>>();
            for(DataMap pubMetadataObj : pubMetadataList){
                String sortId = String.valueOf(pubMetadataObj.get("sortId"));
                List<DataMap> filedList = new ArrayList<DataMap>();
                if(fieldListMap.containsKey(sortId)){
                    filedList = fieldListMap.get(sortId);
                }
                filedList.add(pubMetadataObj);
                fieldListMap.put(sortId,filedList);
            }
            log.info("字段分类整理 ->  根据表整理完成");
            data.put("fieldListMap",fieldListMap);
            if(fieldListMap.size()!=sortInfoList.size()){
                log.error("["+sysEname+"]下按字段分组整理后的表个数["+fieldListMap.size()+"]不等于["+sortInfoList.size()+"]，请检查不对应的关系！");
            }
            data.put("fieldTypeMap",getFieldTypeMap(databaseType));
            data.put("fieldConstraintMap",getFieldConstraintMap(databaseType));

            //5、生成栏目目录
            if(!FileOperate.getInstance().checkFolder(createFileRoot)){
                boolean fte = FileOperate.getInstance().newCreateFolder(createFileRoot);//创建目录
                log.info("文件目录创建完成：" + createFileRoot + " return " + fte);
            }
            String fileName = sysCname+"-数据库设计说明书.doc";
            String createFilePath = createFileRoot + "/" +fileName;
            String downloadFilePath = fileDownloadUrl+"/atta/" +sysEname+"/"+ nowDataStr + "/" +fileName;
            log.info("文件生成名称 ->  " + fileName);
            log.info("文件生成地址 ->  " + createFilePath);

            //3、根据模板生成文件
            String templateFile = "plateform/file/file-database.xml";
            String fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);
            boolean flag = FileOperate.getInstance().newCreateFile(createFilePath, fileContent);
            log.info("文件使用模板 ->  [" + templateFile + "]生成[" + fileName + "] " + flag);
            log.info("文件下载地址 ->  " + downloadFilePath);
            msgJson.put("fileNameDoc",fileName);
            msgJson.put("downloadDoc",downloadFilePath);

            String fileNameHtml = sysCname+"-数据库设计说明书.html";
            templateFile = "plateform/file/file-database.html";
            createFilePath = createFileRoot + "/" +fileNameHtml;
            downloadFilePath = fileDownloadUrl+"/atta/"  +sysEname+"/"+ nowDataStr + "/" +fileNameHtml;
            fileContent = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateFile);
            flag = FileOperate.getInstance().newCreateFile(createFilePath, fileContent);
            log.info("文件使用模板 ->  [" + templateFile + "]生成[" + fileNameHtml + "] " + flag);
            msgJson.put("downloadHtml",downloadFilePath);
            msgJson.put("fileNameHtml",fileNameHtml);

            msg = new ResultMsg("T", msgJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
            msg = new ResultMsg("F", "生成数据库文档失败！");
        }
        return msg;
    }

    /**
     * 生成数据字典列表文件【数据字典 科目列表 js文件】【按系统】
     */
    @RequestMapping(value = "createDictCateList", method = "post")
    public ResultMsg createDictCateList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultMsg msg = new ResultMsg("F", "生成失败");
        Map<String, String> paramMap = getParameterMap(request);
        String sysEname = paramMap.get("sysEname");
        //1、获取参数
        if (Validator.isNull(sysEname)) {
            return new ResultMsg("F", "系统标识不能为空");
        }
        String fileDirectory = ToolsUtil.getInstance().getLocalByKey("config.properties", "js_path");//生成的js文件存放目录

        Map<String, Object> dictCateMap = new HashMap<String, Object>();
        dictCateMap.put("modelTypes", "s_dictDataCate");
        dictCateMap.put("datasource", "plateform");
        dictCateMap.put("dictDataCate.w_sysEname", sysEname);
        log.info("系统【" + sysEname + "】数据字典列表查询->" + dictCateMap);
        List<DataMap> list = (List<DataMap>) CreateTableSql.instance().init(dictCateMap);
        String sysPass = ConfigUtil.getInstance().interfacePass();
        Map<String, Object> data = new HashMap<String, Object>();
        if (null == list) {
            log.info("dictCateList 获取失败！！！");
            msg = new ResultMsg("F", "生成失败！");
        } else {
            data.put("total", list.size());
            JSONArray jsonArray = new JSONArray();
            if (list.size() > 0) {
                for (Object obj : list) {
                    DataMap dataCate = (DataMap) obj;
                    Map<String, String> item = new HashMap<>();
                    item.put("cateId", String.valueOf(dataCate.get("cateId")));
                    item.put("cateEname", String.valueOf(dataCate.get("cateEname")));
                    item.put("cateCname", String.valueOf(dataCate.get("cateCname")));
                    item.put("cateRemark", StrUtil.doNull(String.valueOf(dataCate.get("cateRemark")), ""));
                    item.put("viewType", StrUtil.doNull(String.valueOf(dataCate.get("viewType")), ""));
                    jsonArray.add(item);
                }
            }
            data.put("rows", jsonArray);
            String fileName = "dict-cate-list-" + sysEname + ".js";
            log.info("系统【" + sysEname + "】数据字典列表生成js文件 start ->" + fileName);
            String classFilePath = ToolsUtil.getClassLoaderPath().replaceAll("/WEB-INF/classes/", "");
            String filePath = StrUtil.doNull(fileDirectory, classFilePath);
            filePath+=filePath.endsWith("/")?"":"/";
            filePath+="common/" + sysEname + "/";
            FileOperate.getInstance().newCreateFolder(filePath);//创建文件目录
            String enstr = JSONObject.fromObject(data).toString();
            log.info("系统【" + sysEname + "】数据字典列表数据 ->" + enstr);
            boolean fileResult = FileOperate.getInstance().newCreateFile(filePath+ fileName, enstr);
            log.info("系统【" + sysEname + "】数据字典列表生成js文件 end ->" + fileResult);
            if(fileResult){
                msg = new ResultMsg("T", "生成数据字典列表文件成功！");
            }
        }
        return msg;
    }

    /**
     * 生成数据字典科目子项js文件【数据字典 指定科目项目下条目数据js文件】
     */
    @RequestMapping(value = "createDictCateItemList", method = "post")
    public ResultMsg createDictCateItemList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultMsg msg = new ResultMsg("F", "生成失败");
        Map<String, String> paramMap = getParameterMap(request);
        String viewType = StrUtil.doNull(String.valueOf(paramMap.get("viewType")),"");
        String doCode = "";
        String sysEname = paramMap.get("sysEname");
        String cateEname = paramMap.get("cateEname");
        String fileDirectory = ToolsUtil.getInstance().getLocalByKey("config.properties", "js_path");//生成的js文件存放目录
        if (!StrUtil.isNull(cateEname)) {
            String fileName = "dict-data-" + cateEname.toLowerCase() + ".js";

            Map<String, Object> cateItemMap = new HashMap<String, Object>();
            cateItemMap.put("modelTypes", "s_dictDataItem");
            cateItemMap.put("dictDataItem.w_cateEname",cateEname);
            cateItemMap.put("dictDataItem.w_itemStatus","1");
            cateItemMap.put("orderBy","item_value asc");
            cateItemMap.put("datasource","plateform");
            if(cateEname.indexOf("area")>-1){
                cateItemMap.put("dictDataItem.wn_treeLevel","4");//地区数据字典暂时不获取第4级数据
            }
            log.info("系统【" + sysEname + "】数据字典科目【"+cateEname+"】值条目列表查询->" + cateItemMap);
            List<DataMap> list = (List<DataMap>) CreateTableSql.instance().init(cateItemMap);
            String enstr = "";
            if (null == list) {
                JSONObject jsonObject = JSONObject.fromObject("{}");
                log.info("数据字典[" + cateEname + "]数据查询无结果！");
                msg = new ResultMsg("F", "生成失败！");
            } else {
                JSONArray jsonArray = JSONArray.fromObject(list);
                log.info("数据字典[" + cateEname + "]查询结果转换要求【普通key-value】");
                fileName = "dict-data-" + cateEname.toLowerCase() + ".js";
                jsonArray = listToDataJson(list);
                enstr = jsonArray.toString();
                log.info("数据字典[" + cateEname + "]转换结果：" + enstr);
                log.info("开始生成json文件：" + fileName);
                boolean fileResult = createJsFile(fileDirectory,cateEname,fileName,enstr);
                log.info("数据字典[" + cateEname + "]普通json文件生成结果：" + fileResult);
                if(fileResult){
                    //特殊结构的
                    if("1".equals(viewType)){
                        log.info("数据字典[" + cateEname + "]查询结果转换要求【三级联动】");
                        if ("area".equals(cateEname)) {
                            fileName = "jquery.cityselect-dict-data.js";
                        } else {
                            fileName = "jquery.select-dict-data-" + cateEname + ".js";
                        }
                        jsonArray =  getDictItemThreeChange(list);//三级联动
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("citylist",jsonArray);
                        enstr = jsonObject.toString();
                        log.info("数据字典[" + cateEname + "]转换【三级联动】结果：" + enstr);
                    }else if("2".equals(viewType)){
                        log.info("数据字典[" + cateEname + "]查询结果转换要求【树形结构】");
                        fileName = "dict-data-" + cateEname.toLowerCase() + "-tree.js";
                        jsonArray = listToTreeDataJson(list,"0");
                        enstr = String.valueOf(jsonArray.toString());
                        log.info("数据字典[" + cateEname + "]转换【树形结构】结果：" + enstr);
                    }
                    log.info("开始生成json文件：" + fileName);
                    fileResult = createJsFile(fileDirectory,cateEname,fileName,enstr);
                    log.info("数据字典[" + cateEname + "]json文件生成结果：" + fileResult);
                    if(fileResult){
                        msg = new ResultMsg("T", "生成数据字典文件成功！");
                    }
                }
            }
        } else {
            log.info("请求的cateEname参数为空，不能生成json文件");
            msg = new ResultMsg("F", "请求的cateEname参数不能为空");
        }
        return msg;
    }
    private boolean createJsFile(String fileDirectory,String cateEname,String fileName,String enstr){
        String classFilePath = ToolsUtil.getClassLoaderPath().replaceAll("/WEB-INF/classes/", "");
        String filePath = StrUtil.doNull(fileDirectory, classFilePath);
        filePath+=filePath.endsWith("/")?"":"/";
        filePath+="js/dictData/" ;
        FileOperate.getInstance().newCreateFolder(filePath);//创建文件目录
        boolean fileResult = FileOperate.getInstance().newCreateFile(filePath+fileName, enstr);
        return fileResult;
    }
    /**
     * 纯树形结构的
     */
    private JSONArray listToTreeDataJson(List<DataMap> listData,String pid){
        JSONArray jsonArray = new JSONArray();
        //list生成JSON格式的树
        for(DataMap dms:listData){
            String fatherId = String.valueOf(dms.get("fatherId"));
            String treeLevel = String.valueOf(dms.get("treeLevel"));
            String itemValue = String.valueOf(dms.get("itemValue"));
            String itemId = String.valueOf(dms.get("itemId"));
            String itemText = String.valueOf(dms.get("itemText"));
//            String nodeIcon = StrUtil.doNull(String.valueOf(objMap.get("nodeIcon")),"");
            if(fatherId.equals(pid)){
                JSONObject jsonObj = new JSONObject();
                jsonObj.put("fatherId",fatherId);
                jsonObj.put("treeLevel",StrUtil.doNull(treeLevel,""));
                jsonObj.put("itemId",itemId);
                jsonObj.put("itemText",itemText);
                jsonObj.put("itemValue",itemValue);
//                jsonObj.put("nodeIcon",nodeIcon);
//                jsonObj.put("nodeName",nodeName);
                JSONArray array = listToTreeDataJson(listData,itemId);
                if(array.size()>0){
                    jsonObj.put("items",array);
                }
                jsonArray.add(jsonObj);
            }
        }
        return jsonArray;
    }
    /**
     * 纯json结构的
     */
    private JSONArray listToDataJson(List<DataMap> listData){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObj_def = new JSONObject();
        jsonObj_def.put("id","");
        jsonObj_def.put("text","--请选择--");
        jsonObj_def.put("remark","");
        jsonObj_def.put("item","{}");
        jsonArray.add(jsonObj_def);
        JSONObject jsonObj = null;
        //list生成JSON格式的树
        for(DataMap dms:listData){
//            String fatherId = String.valueOf(dms.get("fatherId"));
//            String treeLevel = String.valueOf(dms.get("treeLevel"));
            String itemValue = String.valueOf(dms.get("itemValue"));
            String itemText = String.valueOf(dms.get("itemText"));
            String itemRemark = String.valueOf(dms.get("itemRemark"));

            DataMap otherMap = new DataMap();
            otherMap.putAll(dms);
            otherMap.remove("orgId");
            otherMap.remove("deptId");
            otherMap.remove("fatherId");
            otherMap.remove("fatherValue");
            otherMap.remove("fullCname");
            otherMap.remove("fullEname");
            otherMap.remove("delStatus");
            otherMap.remove("createUser");
            otherMap.remove("itemId");
            otherMap.remove("createTime");
            otherMap.remove("updateTime");
            otherMap.remove("updateCount");
            otherMap.remove("updateUser");
            otherMap.remove("sysName");
            otherMap.remove("itemStatus");

            jsonObj = new JSONObject();
            jsonObj.put("id",itemValue);
            jsonObj.put("text",itemText);
            jsonObj.put("remark",StrUtil.doNull(itemRemark,""));
            jsonObj.put("item",JSONObject.fromObject(otherMap));
            jsonArray.add(jsonObj);
        }
        return jsonArray;
    }
    //解决三级联动子级
    private JSONArray getDictItemThreeChange(List<DataMap> listData) {
        JSONArray jsonArray = new JSONArray();
        for(DataMap dms:listData) {
            String fatherId = String.valueOf(dms.get("fatherId"));
            String itemId = String.valueOf(dms.get("itemId"));
            String itemValue = String.valueOf(dms.get("itemValue"));
            String itemText = String.valueOf(dms.get("itemText"));
            if("0".equals(fatherId)){
                Map map = new HashMap();
                map.put("p", itemValue + ":" + itemText);
                List jss = getDictItemThreeChild("n","a",itemId,listData);
                if (!Validator.isEmpty(jss)) {
                    map.put("c", jss);
                }
                jsonArray.add(map);
            }
        }
        return jsonArray;
    }
    //解决三级联动子级
    private List getDictItemThreeChild(String title_key,String title_value,String pid,List<DataMap> listData) {
        List list = new ArrayList();
        if (!Validator.isEmpty(listData)) {
            for(DataMap dms:listData) {
                String fatherId = String.valueOf(dms.get("fatherId"));
                if(pid.equals(fatherId)){
                    String itemId = String.valueOf(dms.get("itemId"));
                    String itemValue = String.valueOf(dms.get("itemValue"));
                    String itemText = String.valueOf(dms.get("itemText"));
                    Map map = new HashMap();
                    map.put(title_key, itemValue + ":" + itemText);
                    if(!"s".equals(title_key)){
                        List jss = getDictItemThreeChild("s","d",itemId,listData);
                        if (!Validator.isEmpty(jss)){
                            map.put(title_value, jss);
                        }
                    }
                    list.add(map);
                }
            }
        }
        return list;
    }

    /**
     * 获取数据库字段类型定义Map
     * @param databaseType
     * @return
     */
    private Map<String,String> getFieldTypeMap(String databaseType){
        Map<String,String> map = new HashMap<String,String>();
         if ("mysql".equals(databaseType)) {
             map.put("1","int");
             map.put("2","bigint");
             map.put("3","float");
             map.put("4","char");
             map.put("5","varchar");
             map.put("6","datetime");
             map.put("7","text");
             map.put("8","decimal");
         } else {
             map.put("1","number");
             map.put("2","long");
             map.put("3","double");
             map.put("4","char");
             map.put("5","varchar2");
             map.put("6","date");
             map.put("7","text");
         }
        return map;
    }

    /**
     * 获取数据库字段的约束说明
     * @param databaseType
     * @return
     */
    private Map<String,String> getFieldConstraintMap(String databaseType){
        Map<String,String> map = new HashMap<String,String>();
        map.put("1","主键");
        map.put("2","非空");
        map.put("3","可空");
        map.put("4","联合主键");
        return map;
    }

    /**
     * 根据sokect端口号，设置ajp端口号
     * @param port
     * @return
     */
    private String getDefaultAjpPort(String port){
        String ajpPort= "";
        if(port.length()==5){
            ajpPort = port.substring(0,3)+"2"+port.substring(4,5);
        }else{
            ajpPort=port.substring(0,2)+"19";
        }
        return ajpPort;
    }

    /**
     * 获取微服务相关配置，以备生成工程配置相关相同的服务注册（zuul、eureka）等所需
     * @return
     */
    private Map<String,String> getDefaultMinServiceConfig(){
        Map<String, String> propAppMap = getPropertiesMapByFilePath("application.properties");
        Map<String, String> propRedisMap = getPropertiesMapByFilePath("redis/redis-config.properties");

        Map<String,String> minServMap = new HashMap<>();
        minServMap.put("eurekaUserName",StrUtil.doNull(propAppMap.get("myauth.eureka.username"),"admin"));
        minServMap.put("eurekaPassword",StrUtil.doNull(propAppMap.get("myauth.eureka.password"),"iussoft"));
        minServMap.put("eurekaServerIp",StrUtil.doNull(propAppMap.get("eureka.instance.ip-address="),"127.0.0.1"));
        String serviceEurekaServerUrl = StrUtil.doNull(propAppMap.get("eureka.client.serviceUrl.defaultZone"),"http://127.0.0.1:8761/eureka/");
        minServMap.put("eurekaServerUrl",serviceEurekaServerUrl);
        String serviceEurekaPort = "8761";
        if(serviceEurekaServerUrl.indexOf(":")>-1){
            //从地址配中剥离出端口
            String [] mhs = serviceEurekaServerUrl.split(":");
            String portGourp = mhs[mhs.length-1];
            serviceEurekaPort=portGourp.substring(0,portGourp.indexOf("/"));
        }
        minServMap.put("eurekaServerPort",StrUtil.doNull(propAppMap.get("eureka.instance.port"),serviceEurekaPort));
        minServMap.put("redisMasterIp",StrUtil.doNull(propRedisMap.get("redis_master_ip"),"127.0.0.1"));
        minServMap.put("redisMasterPort",StrUtil.doNull(propRedisMap.get("redis_master_port"),"6379"));
        return minServMap;

    }
    /**
     * 读取class(resources)开始对应的配置文件
     * @param resFilePath 参数如：config/config.properties
     * @return map
     */
    private Map<String, String> getPropertiesMapByFilePath(String resFilePath){
        String filePath = ConfigUtil.getClassLoaderPath();
        filePath+=resFilePath;
        log.info("正在读取配置文件："+filePath);
        Map<String, String> param = new HashMap();
        Properties prop = null;
        FileInputStream fileInput = null;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                prop = new Properties();
                fileInput = new FileInputStream(filePath);
                prop.load(fileInput);
            }
            if (prop!=null) {
                Map<String, String> map = new HashMap(prop);
                Set propertySet = map.entrySet();
                Iterator var11 = propertySet.iterator();

                while(var11.hasNext()) {
                    Object o = var11.next();
                    Map.Entry entry = (Map.Entry)o;
                    param.put(entry.getKey().toString(), entry.getValue().toString());
                }
            }
        } catch (IOException var8) {
            log.error("文件(" + filePath + ")读取失败 key=" + var8.getMessage());
        } finally {
            IOUtils.closeQuietly(fileInput);
        }
        return param;
    }

}
